/**
 * 效率分析图表组件
 * 使用ECharts展示创作效率分析
 */
import React, { useEffect, useRef } from 'react';
import { Card, Spin, Empty, Space, Row, Col, Statistic } from 'antd';
import { ClockCircleOutlined } from '@ant-design/icons';
import * as echarts from 'echarts';
import type { ECharts } from 'echarts';
import { useStatisticsStore } from '@/stores/statistics.store';
import './style.css';

interface EfficiencyChartProps {
  className?: string;
  height?: number;
}

export const EfficiencyChart: React.FC<EfficiencyChartProps> = ({
  className,
  height = 300,
}) => {
  const stageChartRef = useRef<HTMLDivElement>(null);
  const trendChartRef = useRef<HTMLDivElement>(null);
  const stageChartInstance = useRef<ECharts | null>(null);
  const trendChartInstance = useRef<ECharts | null>(null);

  const { efficiencyAnalysis, loading, loadEfficiencyAnalysis } = useStatisticsStore();

  useEffect(() => {
    loadEfficiencyAnalysis();
  }, [loadEfficiencyAnalysis]);

  // 渲染阶段分布饼图
  useEffect(() => {
    if (!stageChartRef.current || loading || !efficiencyAnalysis) return;

    if (!stageChartInstance.current) {
      stageChartInstance.current = echarts.init(stageChartRef.current);
    }

    const { stageBreakdown } = efficiencyAnalysis;

    const option: echarts.EChartsOption = {
      title: {
        text: '创作阶段时间分布',
        left: 'center',
        textStyle: {
          fontSize: 14,
          fontWeight: 'bold',
        },
      },
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c}分钟 ({d}%)',
      },
      legend: {
        orient: 'vertical',
        right: 10,
        top: 'middle',
      },
      series: [
        {
          name: '时间分布',
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2,
          },
          label: {
            show: false,
            position: 'center',
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 16,
              fontWeight: 'bold',
            },
          },
          labelLine: {
            show: false,
          },
          data: [
            {
              value: stageBreakdown.brainstorm,
              name: '头脑风暴',
              itemStyle: { color: '#5470c6' },
            },
            {
              value: stageBreakdown.outline,
              name: '大纲规划',
              itemStyle: { color: '#91cc75' },
            },
            {
              value: stageBreakdown.writing,
              name: '正文写作',
              itemStyle: { color: '#fac858' },
            },
            {
              value: stageBreakdown.optimization,
              name: '优化润色',
              itemStyle: { color: '#ee6666' },
            },
          ],
        },
      ],
    };

    stageChartInstance.current.setOption(option);
  }, [efficiencyAnalysis, loading]);

  // 渲染效率趋势折线图
  useEffect(() => {
    if (!trendChartRef.current || loading || !efficiencyAnalysis) return;

    if (!trendChartInstance.current) {
      trendChartInstance.current = echarts.init(trendChartRef.current);
    }

    const { efficiencyTrend } = efficiencyAnalysis;

    if (efficiencyTrend.length === 0) {
      trendChartInstance.current.clear();
      return;
    }

    const dates = efficiencyTrend.map((item) => item.date);
    const efficiencies = efficiencyTrend.map((item) => item.efficiency);

    const option: echarts.EChartsOption = {
      title: {
        text: '效率趋势（分钟/篇）',
        left: 'center',
        textStyle: {
          fontSize: 14,
          fontWeight: 'bold',
        },
      },
      tooltip: {
        trigger: 'axis',
        formatter: '{b}<br/>{a}: {c} 分钟',
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '10%',
        top: 60,
        containLabel: true,
      },
      xAxis: {
        type: 'category',
        data: dates,
        boundaryGap: false,
        axisLabel: {
          rotate: 45,
          formatter: (value: string) => {
            const date = new Date(value);
            return `${date.getMonth() + 1}/${date.getDate()}`;
          },
        },
      },
      yAxis: {
        type: 'value',
        axisLabel: {
          formatter: '{value} 分钟',
        },
        splitLine: {
          lineStyle: {
            type: 'dashed',
          },
        },
      },
      series: [
        {
          name: '效率',
          type: 'line',
          data: efficiencies,
          smooth: true,
          lineStyle: {
            width: 3,
            color: '#1890ff',
          },
          itemStyle: {
            color: '#1890ff',
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: 'rgba(24, 144, 255, 0.3)' },
              { offset: 1, color: 'rgba(24, 144, 255, 0.05)' },
            ]),
          },
        },
      ],
    };

    trendChartInstance.current.setOption(option);
  }, [efficiencyAnalysis, loading]);

  // 响应式处理
  useEffect(() => {
    const handleResize = () => {
      stageChartInstance.current?.resize();
      trendChartInstance.current?.resize();
    };

    window.addEventListener('resize', handleResize);

    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, []);

  // 清理
  useEffect(() => {
    return () => {
      stageChartInstance.current?.dispose();
      trendChartInstance.current?.dispose();
    };
  }, []);

  return (
    <Card
      className={`efficiency-chart ${className || ''}`}
      title={
        <Space>
          <ClockCircleOutlined />
          <span>创作效率分析</span>
        </Space>
      }
    >
      <Spin spinning={loading}>
        {!efficiencyAnalysis && !loading ? (
          <Empty description="暂无数据" style={{ padding: '40px 0' }} />
        ) : (
          <>
            {/* 统计概览 */}
            {efficiencyAnalysis && (
              <Row gutter={16} style={{ marginBottom: 24 }}>
                <Col span={8}>
                  <Statistic
                    title="平均耗时"
                    value={efficiencyAnalysis.avgTimePerArticle}
                    suffix="分钟/篇"
                    valueStyle={{ color: '#1890ff' }}
                  />
                </Col>
                <Col span={8}>
                  <Statistic
                    title="高效时段"
                    value={efficiencyAnalysis.peakHours.length}
                    suffix="个"
                    valueStyle={{ color: '#52c41a' }}
                  />
                </Col>
                <Col span={8}>
                  <div>
                    <div style={{ color: 'rgba(0,0,0,0.45)', fontSize: 14 }}>
                      高效时段
                    </div>
                    <div style={{ fontSize: 20, fontWeight: 600, color: '#722ed1' }}>
                      {efficiencyAnalysis.peakHours.map((h) => `${h}:00`).join(', ')}
                    </div>
                  </div>
                </Col>
              </Row>
            )}

            {/* 图表 */}
            <Row gutter={16}>
              <Col xs={24} lg={12}>
                <div ref={stageChartRef} style={{ width: '100%', height: `${height}px` }} />
              </Col>
              <Col xs={24} lg={12}>
                <div ref={trendChartRef} style={{ width: '100%', height: `${height}px` }} />
              </Col>
            </Row>
          </>
        )}
      </Spin>
    </Card>
  );
};

export default EfficiencyChart;
